'use strict'
import React, { Component} from 'react';
import RootSiblings from 'react-native-root-siblings'
import DialogContainer from './DialogContainer';

let sibling = undefined

export default class Dialog extends Component {

    static displayName = 'Dialog';
    static propTypes = DialogContainer.propTypes;

    static show = (options) => {

        sibling = new RootSiblings(
            <DialogContainer
                {...options}
                visible={true}
                callBackClose = {()=>{Dialog.hide()}}
            />
        );
        return sibling;
    };

    static hide = () => {
        if (sibling instanceof RootSiblings) {
            sibling.destroy();
        } else {
            console.warn(`Dialog.hide expected a \`RootSiblings\` instance as argument.\nBut got \`${typeof sibling}\` instead.`);
        }
    };

    _dialog = null;

    constructor(props) {
        super(props);
        this.state = {
            visible: this.props.visible,
        };
    };

    _open = ()=>{
        this.setState({
            visible:true
        })
    }

    _close = () => {
        this.setState({
            visible:false
        })
    }

    componentDidMount = () => {
        this._dialog = new RootSiblings(
            <DialogContainer ref={(obj) =>{this.container = obj}}
                                 {...this.props}
                                 visible={typeof(this.props.visible) != 'undefined'?this.props.visible : this.state.visible}
                                 callBackClose = {this._close}
                                 />
        );
    };

    componentDidUpdate(){
        this._dialog.update(
            <DialogContainer ref={(obj) =>{this.container = obj}}
                                    {...this.props}
                                    visible={typeof(this.props.visible) != 'undefined' ? this.props.visible : this.state.visible}                                    
                                    callBackClose = {this._close}
            />
        );
    }

    componentWillUnmount = () => {
        this._dialog.destroy();
    };

    render(){
        return null;
    }

}

export {
    RootSiblings as Manager
};
